package com.example.customviewprojdct.view.class1

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt
import com.example.customviewprojdct.extensions.dp
import kotlin.math.min

/**
 * 简单饼状图
 */
class SinglePieView @JvmOverloads constructor(
    context: Context,
    attribute: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attribute, defStyleAttr) {
    companion object {
        val RADIUS = 150.dp
    }

    val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    //半径
    private var currentRadius = 0

    //最大比例
    var maxRadio = 0

    //饼图条目
    val itemList = mutableListOf<PieItem>()

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        currentRadius = min(w, h) / 2
    }

    override fun onDraw(canvas: Canvas) {
        var startAngle = 270f
        for ((index, item) in itemList.withIndex()) {
            paint.color = item.color
            val angle = radioTransform(item.radio)
            canvas.drawArc(
                width / 2f - currentRadius,
                height / 2f - currentRadius,
                width / 2f + currentRadius,
                height / 2f + currentRadius,
                startAngle,
                angle,
                true,
                paint
            )
            startAngle += angle
        }
    }

    /**
     * 比例转换，100 -> 360
     */
    private fun radioTransform(radio: Int): Float {
        return if (maxRadio == 0) 0f else {
            radio / maxRadio.toFloat() * 360f
        }
    }

    private fun updateMaxRadio() {
        this.maxRadio = this.itemList.fold(0) { acc: Int, pieItem: PieItem -> acc + pieItem.radio }
    }

    fun setData(list: List<PieItem>) {
        this.itemList.clear()
        this.itemList.addAll(list)
        updateMaxRadio()
        invalidate()
    }

    fun updateData(id: Int, block: PieItem?.() -> Unit) {
        block(this.itemList.find { it.id == id })
        updateMaxRadio()
        invalidate()
    }

    /**
     * 饼图条目
     */
    data class PieItem(
        val id: Int,
        @ColorInt var color: Int,
        var radio: Int
    )

}